package com.bjsxt.homework4;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class SaleTicket {

    private int count;

    private Lock lock = new ReentrantLock();

    private Condition c1 = lock.newCondition();
    private Condition c2 = lock.newCondition();
    private Condition c3 = lock.newCondition();

    public SaleTicket(int count) {
        this.count = count;
    }

    /*public void sale() {
        //当前还有票就继续卖票
        while (count > 0) {
            lock.lock();
            try {
                //双层保险
                if (count > 0) {
                    System.out.println(Thread.currentThread().getName() + "：" + count);
                    count--;
                }
            } finally {
                lock.unlock();
            }
        }
    }*/

    public void sale1() {
        //当前还有票就继续卖票
        while (count > 0) {
            lock.lock();
            c2.signalAll();
            c3.signalAll();
            try {
                System.out.println(Thread.currentThread().getName() + "：" + count);
                count--;
                try {
                    if (count > 0) {
                        c1.await();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            } finally {
                lock.unlock();
            }
        }
    }

    public void sale2() {
        //当前还有票就继续卖票
        while (count > 0) {
            lock.lock();
            c1.signalAll();
            c3.signalAll();
            try {
                System.out.println(Thread.currentThread().getName() + "：" + count);
                count--;
                try {
                    if (count > 0) {
                        c2.await();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            } finally {
                lock.unlock();
            }
        }
    }

    public void sale3() {
        //当前还有票就继续卖票
        while (count > 0) {
            lock.lock();
            c1.signalAll();
            c2.signalAll();
            try {
                System.out.println(Thread.currentThread().getName() + "：" + count);
                count--;
                try {
                    if (count > 0) {
                        c3.await();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            } finally {
                lock.unlock();
            }
        }
    }
}
